import { ref } from 'vue';
import { defineStore } from 'pinia';

/**
 * 数据状态管理
 */
export const useSsqCartStore = defineStore('SsqCart', () => {
    /**
     * 购物车数据
     */
    const cart = ref([]);
    /**
     * 添加到购物车
     * @param {Object} item - 需要添加的项
     */
    const addCart = (item) => {
        cart.value.push(item);
        window.localStorage.setItem('ssq_cart', JSON.stringify(cart.value));
        console.log('【SsqCart】addToCart ', item);
    }
    /**
     * 获取购物车数据
     * @returns {Array} - 购物车数据
     */
    const getCart = () => {
        if (cart.value.length === 0) {
            cart.value = JSON.parse(window.localStorage.getItem('ssq_cart') ?? '[]');
        }
        return cart.value;
    }
    /**
     * 清空购物车
     */
    const clearCart = () => {
        cart.value = [];
        window.localStorage.removeItem('ssq_cart');
        console.log('【SsqCart】clearCart');
    }

    return {
        addCart,
        getCart,
        clearCart,
    }
})
